#!/usr/bin/env python

## Main Entry Point for Google app Server
#
# @defgroup ServerSide Python Server Backend on GooGle app Engine
# This groups all material in pysrc folder which is uploaded to Google cloud
#
# Copyright 2009 Avidys Inc.
#
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from server.RPCMethods import RPCMethods 
from server.WebService import WebService

from server.Utils import *
from model.Model import *
from model.Server import createN

## Main Class handle all request for /ws
#
# @ingroup ServerSide
#      
class Main(WebService): # webapp.RequestHandler
    
    def __init__(self):
        webapp.RequestHandler.__init__(self)
        self.methods = RPCMethods()
                
    ## Generate the return
    #
    def generationPhase (self):
        ''' to avoid re-execution in case of reload'''
        logging.info("Generate ")
        createN(100)
        logging.info( "End CreateN" )

#        try:
#            self.pageID = self.path_list[1] # / removed
#        except:
#            self.pageID = self.path_list[0] # / removed
#            if self.pageID == '' or self.pageID == 'index.html' or self.pageID == 'index.htm': self.pageID="0.0"
#        self.session.set("pageID",self.pageID)
#        logging.info(self.pageID+" - ")


    ## Send back to CLient
    #
    def outputPhase(self):
        logging.info("Output")
        generationDetails=str(self.getGenerationDetails())
        if self._checkPath():
#            id=self.pageID=self.session.get("pageID")
            func = getattr(self.methods, self.action, None)
   
            if not func: 
                self.abort("Function not found")
            else:
#                logging.info('post :'+self.request.body)
                try:
                    args = json.loads(self.request.body)
                except:
                    args = self.getArgs()

                logging.info('function: ['+self.action+'] args :'+str(args))
                if "senderID" in args: del(args["senderID"])
                try:
                    res=func(*args)
                    return self.ok(res)
                except:
                    self.abort("Incorrect function call")
                    return

    
application = webapp.WSGIApplication([('/.*', Main)], debug=True) #/'+WS_ID+'


## Main without profiling
# for production
def real_main():
    run_wsgi_app(application)

## Profiling through HTTP
# This is the main function for profiling 
# We've renamed our original main() above to real_main()
def http_profile_main():
    import cProfile, pstats
    prof = cProfile.Profile()
    prof = prof.runctx("real_main()", globals(), locals())
    print "</center><div class='profile'><pre>"
    stats = pstats.Stats(prof)
    stats.sort_stats("time")  # Or cumulative
    stats.print_stats(80)  # 80 = how many to print
    # The rest is optional.
    stats.print_callees()
    stats.print_callers()
    print "</pre></div>"

## Profiling through logging
# This is the main function for profiling 
# We've renamed our original main() above to real_main()
def logging_profile_main():
    import cProfile, pstats, StringIO
    prof = cProfile.Profile()
    prof = prof.runctx("real_main()", globals(), locals())
    stream = StringIO.StringIO()
    stats = pstats.Stats(prof, stream=stream)
    stats.sort_stats("time")  # Or cumulative
    stats.print_stats(80)  # 80 = how many to print
    # The rest is optional.
    # stats.print_callees()
    # stats.print_callers()
    logging.info("Profile data:\n%s", stream.getvalue())

# choice of main
main=real_main

if __name__ == "__main__":
    main() # main is actually assign above and reoriented to one of the effector function

